package com.shushan.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.android.net.bean.NetRetBean;
import com.android.net.util.NetToastUtil;
import com.shushan.login.LoginOrRegisterActivity;
import com.shushan.shushanbao.R;
import com.shushan.ui.PopupDialog;
import com.shushan.ui.WaitDialog;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToastUtils;


/**
 * @ClassName: BaseFragmentActivity
 * @Desciption: viewpage继承的基类
 * @author: yichaohua
 * @date: 2018-01-05
 */
public class BaseFragmentActivity extends FragmentActivity {

    private static final String TAG = "BaseFragmentActivity";

    private WaitDialog mWaitDialog;
    private boolean isAllowBack = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityStackManager.getActivityStackManager().pushActivity(this);

        mWaitDialog = new WaitDialog(this, R.style.Dialog_Translucent_Background);
    }

    @Override
    protected void onPause() {
        super.onPause();

        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        Log.i(TAG,"isChildControl=" + isChildControl + " isAllowBack=" + isAllowBack);
        if(!isAllowBack && isChildControl){
            ActivityManager activityManager = (ActivityManager) getApplicationContext()
                    .getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.moveTaskToFront(getTaskId(), 0);
        }

        isAllowBack = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ActivityStackManager.getActivityStackManager().popActivity(this);

        if(mWaitDialog != null  && !isFinishing()){
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    protected void startActivityAllow(Intent intent) {
        if(intent == null){
            return;
        }

        isAllowBack = true;
        startActivity(intent);
    }

    protected void startActivity(Class<? extends Activity> cls){
        isAllowBack = true;
        startActivity(new Intent(this,cls));
    }

    protected void startActivityForResult(Class<? extends Activity> cls){
        isAllowBack = true;
        startActivityForResult(new Intent(this,cls),100);
    }

    /**
     * 跳转Activity
     * skip Another Activity
     *
     * @param cls
     */
    protected void skipAnotherActivity(Class<? extends Activity> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
        onBackAction();
    }

    /**
     * 退出应用
     * called while exit app.
     */
    public void exitLogic() {
        ActivityStackManager.getActivityStackManager().popAllActivity();//remove all activity.
        System.exit(0);//system exit.
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            //点击空白位置 隐藏软键盘
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super .onTouchEvent(event);
    }

    protected void onBackAction(){
        if(mWaitDialog != null){
            mWaitDialog.dismiss();
        }

        finish();
    }

    protected void onBackAction(int resultCode) {
        if(mWaitDialog != null){
            mWaitDialog.dismiss();
        }

        setResult(resultCode);
        finish();
    }

    protected void showToast( String text){
        ToastUtils.showToast(this,text);
    }

    protected void showNetError(NetRetBean netRetBean){
        Log.e(TAG,"netRetBean=" + netRetBean.toString());

        if(netRetBean.getServerCode() == 304){
            showHasLoginDialog();
            return;
        }

        NetToastUtil.requestError(this, netRetBean);
    }

    protected void showNoMsgError(NetRetBean netRetBean) {
        Log.e(TAG, "netRetBean=" + netRetBean.toString());

        if(netRetBean.getServerCode() == 304){
            showHasLoginDialog();
            return;
        }
    }

    private void showHasLoginDialog() {
        final PopupDialog popupDialog = new PopupDialog(this);
        popupDialog.setMessage("发现您的账号：" + SharedPreferencesUtils.getStringDate(
                Constants.LOGIN_MOBILE_SHAREPREFERS_KEY) + "已经在别的设备上登录，是否重新登录？");
        popupDialog.setPositiveButton("去登录", new PopupDialog.DialogOnClickListener() {
            @Override
            public void onClick(View v) {
                isAllowBack = true;
                startActivity(LoginOrRegisterActivity.class);
                SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
            }
        });
        popupDialog.setNegativeButton("取消", new PopupDialog.DialogOnClickListener() {
            @Override
            public void onClick(View v) {
                popupDialog.dismiss();
            }
        });

        if (!isFinishing()) {
            popupDialog.show(getWindow().getDecorView(), ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }

    /**
     * 显示加载动画
     *
     */
    protected void showWaitDialog() {

        if(mWaitDialog != null && !mWaitDialog.isShowing() && !isFinishing()){
            mWaitDialog.show();
        }

    }

    /**
     * 关闭加载动画
     *
     */
    protected void dismissWaitDialog() {
        if (isFinishing()){
            return;
        }

        if(mWaitDialog != null && mWaitDialog.isShowing()){
            mWaitDialog.dismiss();
        }
    }


}
